<?php
namespace Core\Common\Component\Cache;

/**
 * Class RedisTaggedCache
 * @package App\Component\Cache
 * @property RedisStore $store
 */
class RedisTaggedCache extends TaggedCache
{
    public function get($key)
    {
        return $this->store->get($key);
    }

    public function set($key, $value, $ttl)
    {
        foreach ($this->tags as $tag) {
            $this->store->connection()->sAdd($tag, $key);
        }
        $this->store->set($key, $value, $ttl);
    }

    public function mGet($keys)
    {
        return $this->store->mGet($keys);
    }

    public function mSet($items, $ttl)
    {
        if (empty($items)) {
            return true;
        }

        $keys = array_keys($items);
        foreach ($this->tags as $tag) {
            $this->store->connection()->sAdd($tag, ...$keys);
        }
        return $this->store->mSet($items, $ttl);
    }

    public function del($key)
    {
        foreach ($this->tags as $tag) {
            $this->store->connection()->sRem($tag, $key);
        }
        $this->store->del($key);
    }

    public function mDel($keys)
    {
        if (empty($items)) {
            return;
        }

        foreach ($this->tags as $tag) {
            $this->store->connection()->sRem($tag, ...$keys);
        }
        $this->store->mDel($keys);
    }

    public function flush()
    {
        if (empty($this->tags)) {
            return;
        }

        // 删除tag
        foreach ($this->tags as $tag) {
            $members = $this->store->connection()->sMembers($tag);
            if (!empty($members)) {
                foreach (array_chunk($members, 1000) as $membersChunk) {
                    $this->store->connection()->del(...$membersChunk);
                }
            }
        }

        $this->store->connection()->del(...$this->tags);
    }

}